package com.example.hzit.controller;

import com.example.hzit.entity.Content;
import com.example.hzit.service.ContentService;
import com.example.hzit.service.impl.FileService;
import com.example.hzit.utils.PageResult;
import com.example.hzit.vo.ContentVO;
import com.example.hzit.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/content")
public class ContentController {

    @Autowired
    private ContentService contentService;

    @Autowired
    private FileService fileService;

    // 广告列表
    @GetMapping("/list")
    public R getContents() {
        return R.ok().data("list", contentService.list());
    }

    // 条件带分页查询
    @PostMapping("/search/{page}/{pageSize}")
    public R searchContents(@PathVariable Integer page,
                             @PathVariable Integer pageSize,
                             @RequestBody(required = false) ContentVO vo) {
        PageResult<Content> pageResult = contentService.search(page, pageSize, vo);
        return R.ok().data("pr", pageResult);
    }

    // 添加广告
    @PostMapping("/add")
    public R addContent(@RequestBody Content content) {
        boolean success = contentService.add(content);
        return success ? R.ok().message("添加广告成功!") : R.error().message("添加广告失败!");
    }

    // 上传图片
    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String imageUrl = fileService.uploadFile(file);
        return ResponseEntity.ok(imageUrl);
    }

    // 修改广告信息
    @PutMapping("/update")
    public R updateContent(@RequestBody Content content) {
        boolean success = contentService.updateById(content);
        return success ? R.ok().message("修改广告成功!") : R.error().message("修改广告失败!");
    }

    // 删除广告
    @DeleteMapping("/delete/{ids}")
    public R deleteContents(@PathVariable String ids) {
        List<String> contentIds = Arrays.asList(ids.split(","));
        boolean success = contentService.removeByIds(contentIds);
        return success ? R.ok().message("删除广告成功!") : R.error().message("删除广告失败!");
    }
}
